package siddur.traktask.framework;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Component;

import siddur.traktask.entity.ConfigInfo;


@Component
public class ConfigBean {
	
	@PersistenceContext
	private EntityManager em;
	
	private List<ConfigInfo> list;
	
	
	public void loadConfig(){
		list = em.createQuery("from ConfigInfo", ConfigInfo.class).getResultList();
	}
	
	public ConfigInfo getConfig(String configKey){
		for (ConfigInfo sc : list) {
			if(sc.getConfigKey().equals(configKey)){
				return sc;
			}
		}
		return null;
	}
	
	public String getConfigValue(String configKey){
		for (ConfigInfo sc : list) {
			if(sc.getConfigKey().equals(configKey)){
				return sc.getConfigValue();
			}
		}
		return null;
	}
	
	public void setConfigValue(String configKey, String configValue){
		ConfigInfo sc = em.find(ConfigInfo.class, configKey);
		if(sc == null){
			sc = new ConfigInfo();
			sc.setConfigKey(configKey);
		}
		sc.setConfigValue(configValue);
		em.persist(sc);
	}
	
	public void setConfigValue(String configKey, String configValue, boolean reload){
		setConfigValue(configKey, configValue);
		if(reload){
			loadConfig();
		}
	}

}
